package com.gmss.crawler.module.retraction.paperauthor.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmss.crawler.constants.Base;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.enums.CommonEnum;
import com.gmss.crawler.module.retraction.company.service.IRCompanyService;
import com.gmss.crawler.module.retraction.paper.domain.RPaper;
import com.gmss.crawler.module.retraction.paper.service.IRPaperService;
import com.gmss.crawler.module.retraction.paperauthor.domain.RPaperAuthor;
import com.gmss.crawler.module.retraction.paperauthor.service.IRPaperAuthorService;
import com.gmss.crawler.service.AutoRetractionCrawlerService;
import com.gmss.crawler.service.RetractionPaperCrawlerService;
import com.gmss.crawler.task.RetractionPaperTask;
import com.gmss.crawler.utils.CommonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 撤稿论文作者表 前端控制器
 * </p>
 *
 * @author Auto-generator
 * @since 2021-12-20
 */
@Slf4j
@RestController
@RequestMapping("/rPaperAuthor")
public class RPaperAuthorController extends Base {


    @Resource
    private RetractionPaperCrawlerService retractionPaperCrawlerService;

    @Resource
    private IRPaperAuthorService iRPaperAuthorService;

    @Resource
    private AutoRetractionCrawlerService autoRetractionCrawlerService;

    @Resource
    private IRPaperService iRPaperService;

    @Resource
    private IRCompanyService iRCompanyService;

    @Resource
    private RetractionPaperTask retractionPaperTask;

    /**
     * 获取撤稿论文作者、作者工作单位、关键词、摘要
     *
     * @return
     */
    @PostMapping("/getRPaperAuthorByPubMed")
    public String getRPaperAuthorByPubMed(@RequestBody String str) {
        try {
            String startId = null;
            String endId = null;
            List ids = new ArrayList();
            if (StringUtils.isNotBlank(str)) {
                JSONObject jsonObject = JSON.parseObject(str);
                startId = jsonObject.getString("startId");
                endId = jsonObject.getString("endId");
                ids = jsonObject.getJSONArray("ids");
            }
            LambdaQueryWrapper<RPaper> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(startId)) {
                wrapper.ge(RPaper::getId, startId);
            }
            if (StringUtils.isNotBlank(endId)) {
                wrapper.le(RPaper::getId, endId);
            }
            if (CollectionUtils.isNotEmpty(ids)) {
                wrapper.in(RPaper::getId, ids);
            }
            List<RPaper> paperList = iRPaperService.list(wrapper);
//            List<RPaper> paperList = iRPaperService.customRPaper();
            Map<Long, List<RPaperAuthor>> map = retractionPaperCrawlerService.getPubmedById(paperList);
        } catch (Exception e) {
            log.error("getRPaperAuthor Exception：{}", e);
        }
        return respJson(CommonEnum.SUCCESS);
    }

    @PostMapping("/getRPaperAuthorByWebOfScience")
    public String getRPaperAuthorByWebOfScience(@RequestBody String str) {
        String startId = null;
        String endId = null;
        List ids = new ArrayList();
        if (StringUtils.isNotBlank(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            startId = jsonObject.getString("startId");
            endId = jsonObject.getString("endId");
            ids = jsonObject.getJSONArray("ids");
        }
        LambdaQueryWrapper<RPaper> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(startId)) {
            wrapper.ge(RPaper::getId, startId);
        }
        if (StringUtils.isNotBlank(endId)) {
            wrapper.le(RPaper::getId, endId);
        }
        if (CollectionUtils.isNotEmpty(ids)) {
            wrapper.in(RPaper::getId, ids);
        }
        wrapper.orderBy(true, false, RPaper::getId);
        List<RPaper> paperList = iRPaperService.list(wrapper);
        List<Long> errorList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(paperList)) {
            paperList.forEach(rPaper -> {
                try {
                    retractionPaperTask.submit(rPaper);
                    Thread.sleep(CommonUtils.randomRange(1000 * 60, 1000 * 60));
                } catch (Exception e) {
                    log.error("getRPaperAuthorByWebOfScience r_paper.id：{} Exception：{}", rPaper.getId(), e);
                    errorList.add(rPaper.getId());
                }
            });
        }
        return respJson(CommonEnum.SUCCESS, errorList);
    }

    @GetMapping("/rPaperTORPaperAuthor")
    public String rPaperTORPaperAuthor() {
        List<RPaper> paperList = iRPaperService.customRPaper();
        if (CollectionUtils.isNotEmpty(paperList)) {
            for (RPaper rPaper : paperList) {
                RPaperAuthor rPaperAuthor = new RPaperAuthor().builder()
                        .rPaperId(rPaper.getId())
                        .build();
                String allAuthors = rPaper.getAllAuthors();
                if (allAuthors.indexOf(",") > 0 ) {
                    String[] authors = allAuthors.split(",");
                    List<String> authorList = Arrays.asList(authors);
                    for (int i = 0; i < authorList.size(); i++) {
                        rPaperAuthor.setAuthorName(authorList.get(i));
                        rPaperAuthor.setAuthorOther((i + 1));
                        iRPaperAuthorService.save(rPaperAuthor);
                    }
                } else {
                    rPaperAuthor.setAuthorName(allAuthors);
                    rPaperAuthor.setAuthorOther((1));
                    iRPaperAuthorService.save(rPaperAuthor);
                }
            }
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 查询列表
     */
    @PostMapping("/list")
    public String list(@RequestBody RPaperAuthorReqVo rPaperAuthor) {
        final LambdaQueryWrapper<RPaperAuthor> lambda = new QueryWrapper<RPaperAuthor>().lambda();
        this.buildCondition(lambda, rPaperAuthor);
        return respJson(CommonEnum.SUCCESS, iRPaperAuthorService.list(lambda));
    }


    /**
     * 分页查询
     */
    @PostMapping("/page")
    public String page(@RequestBody RPaperAuthorReqVo pageParam) {
        final LambdaQueryWrapper<RPaperAuthor> lambda = new QueryWrapper<RPaperAuthor>().lambda();
        this.buildCondition(lambda, pageParam);
        final IPage<RPaperAuthor> page = iRPaperAuthorService.page(new Page<>(Constants.PAGE_NO, Constants.PAGE_SIZE), lambda);
        return respJson(CommonEnum.SUCCESS, page);
    }

    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<RPaperAuthor> lambda, RPaperAuthorReqVo param) {
        if (null != param.getId()) {
            lambda.eq(RPaperAuthor::getId, param.getId());
        }
        if (null != param.getRPaperId()) {
            lambda.eq(RPaperAuthor::getRPaperId, param.getRPaperId());
        }
        if (!StringUtils.isEmpty(param.getAuthorName())) {
            lambda.eq(RPaperAuthor::getAuthorName, param.getAuthorName());
        }
        if (!StringUtils.isEmpty(param.getAuthorAltName())) {
            lambda.eq(RPaperAuthor::getAuthorAltName, param.getAuthorAltName());
        }
        if (!StringUtils.isEmpty(param.getWorkCompany())) {
            lambda.eq(RPaperAuthor::getWorkCompany, param.getWorkCompany());
        }
        if (null != param.getAuthorOther()) {
            lambda.eq(RPaperAuthor::getAuthorOther, param.getAuthorOther());
        }
        if (null != param.getReportAuthor()) {
            lambda.eq(RPaperAuthor::getReportAuthor, param.getReportAuthor());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(RPaperAuthor::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(RPaperAuthor::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getCreateUser())) {
            lambda.eq(RPaperAuthor::getCreateUser, param.getCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(RPaperAuthor::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(RPaperAuthor::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdateUser())) {
            lambda.eq(RPaperAuthor::getUpdateUser, param.getUpdateUser());
        }
        lambda.orderBy(true, false, RPaperAuthor::getId);
    }


    /**
     * 请求model
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class RPaperAuthorReqVo extends RPaperAuthor {
        private List<String> createTimeList; // 创建时间起止
        private List<String> updateTimeList; // 更新时间起止
    }


}
